package cn.jietuo.netty.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2021/2/27
 * @description: 聊天服务客户端
 */
public class ChatClient {

    public static void main(String[] args) {

        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast("decoder",new StringDecoder())
                                .addLast("encoder",new StringEncoder())
                                .addLast(new ChatClientHandler());
                    }
                });
        try {
            ChannelFuture future = bootstrap.connect("localhost", 9000).sync();
            if (future.isSuccess()){
                Channel channel = future.channel();
                System.out.println("客户端连接成功:"+ channel.localAddress());
                // 客户端输入信息
                Scanner scanner = new Scanner(System.in);
                while (scanner.hasNextLine()){
                    String msg = scanner.nextLine();
                    // 通过channel发送到服务器端
                    channel.writeAndFlush(msg);
                }
//                for (int i = 0; i < 20; i++) {
//                    channel.writeAndFlush("你好呀，你好呀，我在学习netty呢");
//                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
        }

    }
}
